package com.jie.client.core.runnable;

import com.jie.client.core.ClientApplication;
import com.jie.client.core.handler.ClientHandler;
import com.jie.client.core.handler.ClientReaderHandler;
import com.jie.common.http.entity.response.HttpResponse;
import com.jie.common.ssl.constant.SslConstant;
import com.jie.common.ssl.util.AesUtil;
import com.jie.common.util.InputStreamUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.Socket;

/**
 * 客户端用于处理写的Runnable对象
 * @author XieZhiJie
 * @date 2022/04/22 14:52
 */
public class ClientReadHandleRunnable implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(ClientReadHandleRunnable.class);

    private final Socket socket;

    public ClientReadHandleRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (
                InputStream inputStream = this.socket.getInputStream()
        ) {
            handleRead(inputStream);
        } catch (Exception e) {
            logger.error(e.getMessage());
            try {
                this.socket.close();
            } catch (Exception ex) {
                logger.error(e.getMessage());
            }
        }
    }

    /**
     * 处理读
     * @param inputStream 输入流
     * @throws Exception  Exception
     */
    private void handleRead(InputStream inputStream) throws Exception {
        while (ClientApplication.CLIENT_STATE) {
            // 1.读取bytes
            byte[] messageBytes = InputStreamUtil.readMessage(inputStream);
            messageBytes = AesUtil.decryptAndVerifyDigest(messageBytes, ClientHandler.CLIENT_SSL_MESSAGE.getAes(), SslConstant.OPEN_SSL);

            // 2.解析bytes为http响应
            HttpResponse httpResponse;
            try {
                httpResponse = HttpResponse.getHttpResponse(messageBytes);
            } catch (Exception e) {
                this.logger.warn("httpResponse解析失败!");
                httpResponse = null;
            }

            // 3.客户端处理响应
            if (httpResponse != null) {
                ClientReaderHandler.handleResponse(httpResponse);
            }

        }
    }

}
